package co.yixiang.retail.biz.user.controller;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import co.yixiang.common.core.api.ApiResult;
import co.yixiang.common.core.api.YshopException;
import co.yixiang.common.core.exception.BadRequestException;
import co.yixiang.common.mproot.dozer.service.IGenerator;
import co.yixiang.common.security.domain.JwtUser;
import co.yixiang.common.security.utils.SecurityUtils;
import co.yixiang.mall.biz.user.mapper.UserMapper;
import co.yixiang.mall.common.aop.ForbidSubmit;
import co.yixiang.retail.biz.user.mapper.UserExtractMapper;
import co.yixiang.retail.biz.user.mapper.YxSystemStoreMapper;
import co.yixiang.retail.biz.user.sevice.UserExtractService;
import co.yixiang.retail.biz.user.sevice.YxSystemStoreService;
import co.yixiang.retail.common.domain.*;
import co.yixiang.retail.common.dto.UserDto;

import co.yixiang.retail.common.dto.UserExtractDto;
import co.yixiang.retail.common.dto.YxBalanceChangeDto;
import co.yixiang.upms.common.system.vo.UserPassVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "门店认证模块", tags = "门店:认证", description = "认证")
@RequestMapping("/retail")
public class YxRetailAuthController {

    @Value("${rsa.private_key}")
    private String privateKey;
    private final IGenerator generator;
    private final PasswordEncoder passwordEncoder;
    private final YxSystemStoreService storeService;
    private final UserExtractService userExtractService;
    private final UserExtractMapper userExtractMapper;
    private final UserMapper userMapper;
    private final YxSystemStoreMapper yxSystemStoreMapper;

    @GetMapping(value = "/getUser/{phone}")
    public ApiResult<UserInfo> getUser(@PathVariable("phone") String phone) {
        //门店实体类
        List<YxSystemStore> stores=storeService.selectList(phone);
        if (CollectionUtils.isEmpty(stores)){
            throw new YshopException("门店不存在");
        }else if (stores.size()>1){
            throw new YshopException("未知异常，请联系管理员");
        }
        YxSystemStore yxSystemStore = stores.get(0);
        UserDto userDto = storeService.findByPhone(phone);
        userDto.setRetail(yxSystemStore.getId());
        userDto.setRetailType(yxSystemStore.getRetailType());
        userDto.setPermit(yxSystemStore.getPermit());
        HashSet<String> permissions = new HashSet<>();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserDto(userDto);
        userInfo.setPermissions(permissions);
        return ApiResult.ok(userInfo);
    }


    @PostMapping(value = "/check")
    public ApiResult<YxUser> checkUser(@RequestBody Map<String,String> code){
        if (CollectionUtils.isEmpty(code)) {
            throw new YshopException("用戶不存在");
        }
        YxUser yxUser =storeService.checkCode(code);
        return ApiResult.ok(yxUser);
    }



    //修改密码
    @ForbidSubmit
    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo){
        // 密码解密
        RSA rsa = new RSA(privateKey, null);
        String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
        String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
        JwtUser loginUser = SecurityUtils.getLoginUser();
        if (null==loginUser){
           throw new YshopException("登录用户不存在，请重新登陆");
        }
        Long id = loginUser.getId();
        YxUser user=storeService.findUserById(id);
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        //根据用户id修改密码
        storeService.updatePass(id,passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ForbidSubmit
    @ApiOperation("门店佣金提现")
    @PostMapping(value = "/extract")
    public ApiResult<Object> extract(@RequestBody UserExtractDto userExtractDto){
        if (null==userExtractDto.getUid()){
            throw new YshopException("缺少参数");
        }
        JwtUser loginUser = SecurityUtils.getLoginUser();
        if (null==loginUser){

            throw new YshopException("登录用户不存在，请重新登陆");
        }
        userExtractService.save(generator.convert(userExtractDto, UserExtract.class));
        //提现金额
        BigDecimal extractPrice = userExtractDto.getExtractPrice();
        //用户id
        Long uid = userExtractDto.getUid();
        //查询门店当余额
        BigDecimal bigDecimal = storeService.queryStoreBalance(uid);


        storeService.updateBanlance(uid,extractPrice);
        YxBalanceChangeDto yxBalanceChangeDto = new YxBalanceChangeDto();
        yxBalanceChangeDto.setUid(userExtractDto.getUid().intValue());
        yxBalanceChangeDto.setChangeTurn(bigDecimal);
        yxBalanceChangeDto.setChangePut(bigDecimal.subtract(extractPrice));
        yxBalanceChangeDto.setUserFront(extractPrice);
        yxBalanceChangeDto.setType(8);
        yxSystemStoreMapper.insertBlanceChange(yxBalanceChangeDto);
        return ApiResult.ok(HttpStatus.OK,"提现成功");
    }

    @ForbidSubmit
    @ApiOperation("门店充值中心")
    @GetMapping(value = "/{id}")
    public ApiResult<Object> recharge(@PathVariable(value = "id") Integer id){
        Boolean b=storeService.recharge(id);
        return ApiResult.ok(HttpStatus.OK,b.toString());
    }

}
